// eslint-disable-next-line
import {
  getBusinessTable,
  editBusinessRecord
} from '../../api/business'
import {
  BUSINESS_LIST,
  BUSSINESS_CURRENT_ROW,
  BUSSINESS_DATA_COUNT,
  BUSSINESS_HISTORY_DATA,
  BUSSINESS_UPLOAD_LIST
} from '../motations-type'

export default {
  state: {
    businessData: [],
    businessDataCount: null,
    pageSize: 20,
    businessHistoryData: [],
    row: {
      proname: '',
      uname: '',
      puname: '',
      ctime: '',
      data: '',
      test: '',
      trainee: '',
      traintime: '',
      duedate: '',
      traindes: ''
    }
  },
  getters: {
    businessData: state => state.businessData
  },
  mutations: {
    [BUSINESS_LIST] (state, data) {
      state.businessData = data
    },
    [BUSSINESS_CURRENT_ROW] (state, data) {
      state.row = data
    },
    [BUSSINESS_DATA_COUNT] (state, data) {
      state.businessDataCount = data
    },
    [BUSSINESS_HISTORY_DATA] (state, data) {
      state.businessHistoryData = data
    },
    [BUSSINESS_UPLOAD_LIST] (state, data) {
      state.businessData = state.businessData.push(data)
    }
  },
  actions: {
    async getBusinessList ({ commit, rootState }, playload) {
      let data = {}
      let newData = []
      if (Object.keys(playload).length > 0) {
        data = playload
      }
      const resp = await getBusinessTable(data)
      resp.data.data.rows.map((item) => {
        newData = [...newData, {
          id: item.id,
          proname: item.proname,
          uname: item.uname ? item.uname : '-',
          puname: item.puname ? item.puname : '-',
          ctime: item.ctime,
          data: item.data.toString(),
          test: item.test.toString(),
          trainee: item.trainee,
          traintime: item.traintime,
          duedate: item.duedate,
          traindes: item.traindes ? item.traindes : '-'
        }]
      })
      commit(BUSINESS_LIST, newData)
      commit(BUSSINESS_DATA_COUNT, resp.data.data.total)
      if (newData.length < rootState.business.pageSize) {
        commit(BUSSINESS_HISTORY_DATA, newData)
      } else {
        commit(BUSSINESS_HISTORY_DATA, newData.slice(0, rootState.business.pageSize))
      }
    },
    async changeBussinessPage ({ commit, rootState }, index) {
      let data = rootState.business.businessData
      let _start = (index - 1) * rootState.business.pageSize
      let _end = index * rootState.business.pageSize
      commit(BUSSINESS_HISTORY_DATA, data.slice(_start, _end))
    },
    async getBusinessCurrentRow ({ commit, rootState }, row) {
      commit(BUSSINESS_CURRENT_ROW, row)
    },
    async editBussinessData ({ commit, rootState }, playload) {
      let data = {}
      if (Object.keys(playload).length > 0) {
        data = playload
      }
      await editBusinessRecord(data)
    },
    async getBussinessUploadList ({ commit, rootState }, uploadList) {
      commit(BUSSINESS_UPLOAD_LIST, uploadList)
    }
  }
}
